package com.zyy.security.config;

import com.zyy.security.entity.SysRole;
import com.zyy.security.entity.SysUser;
import com.zyy.security.entity.SysUserRole;
import com.zyy.security.service.SysRoleService;
import com.zyy.security.service.SysUserRoleService;
import com.zyy.security.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 用户登录认证信息查询
 * @author Louis
 * @date Nov 20, 2018
 */
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    /*@Autowired
    private UserService userService;*/

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从数据库中取出用户信息
        SysUser user = sysUserService.selectByName(username);
        if (user == null) {
            throw new UsernameNotFoundException("该用户不存在");
        }
        // 用户权限列表，根据用户拥有的权限标识与如 @PreAuthorize("hasAuthority('sys:menu:view')") 标注的接口对比，决定是否可以调用接口
        // 添加权限
        List<SysUserRole> userRoles = sysUserRoleService.listByUserId(user.getId());
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        for (SysUserRole userRole : userRoles) {
            SysRole role = sysRoleService.selectById(userRole.getRoleId());
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }
        return new JwtUserDetails(username, user.getPassword(), authorities);
    }
}